package com.spring.shops.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.spring.shops.constant.MessageConstant;
import com.spring.shops.context.BaseContext;
import com.spring.shops.dao.TzSysUserMapper;
import com.spring.shops.dao.TzSysUserRoleMapper;
import com.spring.shops.model.dto.CaptchaAuthenticationDTO;
import com.spring.shops.model.dto.PasswordDTO;
import com.spring.shops.model.dto.SysUserDTO;
import com.spring.shops.model.entity.TzSysUser;
import com.spring.shops.model.entity.TzSysUserRole;
import com.spring.shops.model.result.IPageIndexImg;
import com.spring.shops.model.result.ServerResponseEntityVoid;
import com.spring.shops.model.vo.SysUserVO;
import com.spring.shops.service.AdminService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private TzSysUserMapper mapper;
    @Autowired
    private TzSysUserRoleMapper userRoleMapper;
    /**
     * 用户登录校验
     *
     * @param authenticationDTO
     * @return
     */
    @Override
    public ServerResponseEntityVoid login(CaptchaAuthenticationDTO authenticationDTO) {
        //获取用户名和密码
        String userName = authenticationDTO.getUserName();
        String passWord = authenticationDTO.getPassWord();

        //1、根据用户名查询数据库中的数据
        TzSysUser user = mapper.getByUsername(userName);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            return ServerResponseEntityVoid.error(MessageConstant.ERROR_CODE,MessageConstant.ACCOUNT_NOT_FOUND);
         //   throw new RuntimeException("账号不存在");
        }
        //密码比对
        // 用户登录时输入的密码
        //获取数据库存储的密码
        String password=user.getPassword();
        //密码校验
        boolean checkpw = BCrypt.checkpw(passWord, password);
        if(checkpw){
            //密码正确校验状态
            if (user.getStatus() == 0) {
                //账号被锁定
                return ServerResponseEntityVoid.error(MessageConstant.ERROR_CODE,MessageConstant.ACCOUNT_LOCKED);
               // throw new RuntimeException("账号被锁定");
            }else {
                System.out.println("查询成功");
                //3、返回实体对象
                return ServerResponseEntityVoid.success(user);
            }
        }else{
            return ServerResponseEntityVoid.error(MessageConstant.ERROR_CODE,MessageConstant.PASSWORD_ERROR);
        }
    }
    /**
     * 添加用户
     * @param tzSysUser
     * @return
     */
    @Override
    public String add(TzSysUser tzSysUser)  {
        //获取密码
        String password = tzSysUser.getPassword();
        // 使用bcrypt生成加密后的哈希值
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        tzSysUser.setPassword(hashedPassword);
        tzSysUser.setStatus((byte) 1);
        tzSysUser.setCreateTime(new Date());
        tzSysUser.setShopId(1L);
        //设置创建当前用户的用户id
        tzSysUser.setCreateUserId(BaseContext.getCurrentId());
        tzSysUser.setMobile("3435663733");
        tzSysUser.setEmail("root@123.com");
        int rows = mapper.insert(tzSysUser);
        if(rows>0){
            return "success";
        }else return "fail";
    }
    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public ServerResponseEntityVoid<IPageIndexImg<SysUserVO>> page(SysUserDTO dto) {
        //获取当前页码
        Long currentPage = dto.getCurrent();
        //获取每页显示的条数
        Long size= dto.getSize();
        //设置分页初始值
        PageHelper.startPage(Math.toIntExact(currentPage), Math.toIntExact(size));
        //调用mapper层进行分页查询
        Page<TzSysUser> userPage=mapper.page(dto);
        //创建IPageIndexImg对象
        IPageIndexImg<SysUserVO> iPageIndexImg=new IPageIndexImg<>();
        iPageIndexImg.setSize(size);
        iPageIndexImg.setTotal(userPage.getTotal());
        iPageIndexImg.setCurrent(currentPage);
        iPageIndexImg.setPages(userPage.getTotal()/size+1);
        //获取所有记录
        List<TzSysUser> result = userPage.getResult();
        List<SysUserVO> data = new ArrayList<>();
        //属性拷贝
        for (TzSysUser user : result) {
            SysUserVO sysUserVO = getSysUserVO(user);
            //加入集合中
            data.add(sysUserVO);
        }
        iPageIndexImg.setRecords(data);
        //返回结果集
        return ServerResponseEntityVoid.success(iPageIndexImg);
    }
    /**
     * 新增用户
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ServerResponseEntityVoid save(SysUserDTO dto) {
        TzSysUser sysUser = getSysUser(dto);
        int rows = mapper.insert(sysUser);
        //获取用户id
        Long userId = sysUser.getUserId();
        //插入用户角色列表
        List<Integer> roleIdList = dto.getRoleIdList();
        if(roleIdList!=null&&!roleIdList.isEmpty()){
            for (Integer roleId : roleIdList) {
                Long roleId2=Long.valueOf(roleId);
                 userRoleMapper.insert(new TzSysUserRole(userId,roleId2));
            }
        }
        return ServerResponseEntityVoid.success();
    }
    /**
     * 根据用户ids删除数据
     * @param userIds
     * @return
     */
    @Override
    @Transactional
    public ServerResponseEntityVoid deleteByIds(List<Long> userIds){
        for (Long userId : userIds) {
            //先删除用户数据
            mapper.deleteByPrimaryKey(userId);
            //然后删除用户角色表中相对应的数据
            userRoleMapper.deleteByUserId(userId);
        }
        return ServerResponseEntityVoid.success();
    }
    /**
     * 根据用户id获取信息
     * @param userId
     * @return
     */
    @Override
    public ServerResponseEntityVoid<SysUserVO> getInfoById(Long userId) {
        //先根据用户id获取用户信息
        TzSysUser tzSysUser = mapper.selectByPrimaryKey(userId);
        SysUserVO sysUserVO = getSysUserVO(tzSysUser);
        //根据用户id获取用户所属的角色id列表
        List<Long> roleIdList=userRoleMapper.selectByUserId(userId);
        sysUserVO.setRoleIdList(roleIdList);
        return ServerResponseEntityVoid.success(sysUserVO);
    }
    /**
     * 更新用户信息
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ServerResponseEntityVoid update(SysUserDTO dto) {
        //根据dto获取entity
        TzSysUser sysUser = getSysUser(dto);
        //更新数据
        sysUser.setUserId(dto.getUserId());
        mapper.updateByPrimaryKey(sysUser);
        //获取用户所属的角色id列表
        List<Integer> roleIdList = dto.getRoleIdList();
        //先删除再插入
       userRoleMapper.deleteByUserId(dto.getUserId());
        for (Integer roleId : roleIdList) {
            Long roleId2=Long.valueOf(roleId);
            userRoleMapper.insert(new TzSysUserRole(dto.getUserId(),roleId2));
        }
        return ServerResponseEntityVoid.success();
    }
    /**
     * 修改用户密码
     * @param dto
     */
    @Override
    public ServerResponseEntityVoid password(PasswordDTO dto) {
        //先获取用户的原密码比较是否正确
        String plainPassword = dto.getPassword();
        //获取当前登录的用户id,根据id查询数据库用户
        TzSysUser tzSysUser = mapper.selectByPrimaryKey(BaseContext.getCurrentId());
        boolean checkpw = BCrypt.checkpw(plainPassword, tzSysUser.getPassword());
        if(checkpw){
            //密码比对成功继续,获取新密码加密更新数据库
            String hashpw = BCrypt.hashpw(dto.getNewPassword(), BCrypt.gensalt());
            tzSysUser.setPassword(hashpw);
            int rows = mapper.updateByPrimaryKey(tzSysUser);
            if(rows>0){
                return ServerResponseEntityVoid.success();
            }else{
                return ServerResponseEntityVoid.error(MessageConstant.ERROR_CODE,MessageConstant.PASSWORD_MODIFY_FAIL);
            }
        }else return ServerResponseEntityVoid.error(MessageConstant.ERROR_CODE,MessageConstant.PASSWORD_ERROR);
    }

    //dto-entity
    public TzSysUser getSysUser(SysUserDTO dto){
        //获取密码
        String password = dto.getPassword();
        // 使用bcrypt生成加密后的哈希值
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        return new TzSysUser(
           dto.getUsername(),hashedPassword,dto.getEmail(),dto.getMobile(),dto.getStatus(),
                BaseContext.getCurrentId(),new Date(),1L

        );
    }
    //实体->vo
    public SysUserVO getSysUserVO(TzSysUser user){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return new SysUserVO(
                user.getUserId(), user.getUsername(), user.getEmail(),user.getMobile(),
                user.getStatus(),null,sdf.format(user.getCreateTime()),user.getShopId()
        );
    }


}
